package com.demandbreakdown.xiyun.common.exception;


import com.demandbreakdown.xiyun.common.base.Result;
import com.demandbreakdown.xiyun.common.base.ResultCode;
import com.demandbreakdown.xiyun.common.base.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author poxz
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理业务异常
     *
     * @param e 异常对象
     * @return Result
     */
    @ExceptionHandler(value = BusinessException.class)
    public Result<String> handleBusinessException(BusinessException e) {
        String message = e.getMessage();
        if (message == null || message.equals(e.getResultCode().getMessage())) {
            message = e.getResultCode().getMessage();
        }
        log.error("业务异常: {}", message);
        return ResultUtils.fail(e.getResultCode().getCode(), message);
    }

    /**
     * 处理参数校验异常
     *
     * @param e 异常对象
     * @return Result
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        String message = fieldError != null ? fieldError.getDefaultMessage() : "参数校验失败";
        log.error("参数校验异常: {}", message);
        return ResultUtils.fail(ResultCode.BAD_REQUEST);
    }

    /**
     * 处理系统异常
     *
     * @param e 异常对象
     * @return Result
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);

        // 根据异常类型返回不同的错误信息
        if (e instanceof IllegalArgumentException) {
            return ResultUtils.fail(ResultCode.PARAMS_ERROR);
        }
        if (e instanceof NullPointerException) {
            return ResultUtils.fail(ResultCode.SYSTEM_ERROR.getCode(), "系统空指针异常");
        }
        if (e.getCause() instanceof java.sql.SQLException) {
            return ResultUtils.fail(ResultCode.SYSTEM_ERROR.getCode(), "数据库异常");
        }

        return ResultUtils.fail(ResultCode.SYSTEM_ERROR);
    }
}
